<?php

namespace app\admin\controller;

use app\admin\model\CustomerAppendix;
use app\admin\model\CustomerCity;
use app\admin\model\CustomerIndustry;
use app\admin\model\CustomerIntention;
use app\admin\model\CustomerLevel;
use app\admin\model\CustomerRipe;
use app\admin\model\CustomerSource;
use app\admin\model\CustomerStatus;
use app\admin\model\CustomerType;
use app\admin\model\FollowStage;
use app\admin\model\FollowStatus;
use app\admin\model\Follow;
use app\admin\model\FollowAppendix;
use app\admin\model\Deliver;
use app\BaseController;
use think\facade\View;
use think\Request;
use app\admin\model\Admin;

class Customer extends BaseController
{

    protected $childrenAdminIds = [];

    public function initialize()
    {
        parent::initialize();
        $customer_city   = CustomerCity::where(['parent_id' => 0])->select();
        $industry        = CustomerIndustry::where(['status' => 1])->select();
        $intention       = CustomerIntention::where(['status' => 1])->select();
        $customer_status = CustomerStatus::where(['status' => 1])->select();
        $customer_type   = CustomerType::where(['status' => 1])->select();
        $customer_level  = CustomerLevel::where(['status' => 1])->select();
        $customer_source = CustomerSource::where(['status' => 1])->select();
        $customer_ripe   = CustomerRipe::where(['status' => 1])->select();
        $admin = Admin::where('id','in',$this->auth->getChildrenAdminIds(true))->where(['status' => 1])->select();
        $follow_stage = FollowStage::where(['status' => 1])->select();
        $follow_status = FollowStatus::where(['status'=>1])->select();
        View::assign('customer_city', $customer_city);
        View::assign('industry', $industry);
        View::assign('intention', $intention);
        View::assign('customer_status', $customer_status);
        View::assign('customer_type', $customer_type);
        View::assign('customer_level', $customer_level);
        View::assign('customer_source', $customer_source);
        View::assign('customer_ripe', $customer_ripe);
        View::assign('admin', $admin);
        View::assign('follow_stage', $follow_stage);
        View::assign('follow_status', $follow_status);
        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
    }

    //显示资源
    public function index(Request $request)
    {

        if ($request->isAjax()) {
            //获取每页显示的条数
            $limit = $request->param('limit');
            //获取当前页数
            $page = $request->param('page');
            $result = \app\admin\model\Customer::with(['CustomerCity','CustomerIntention','CustomerStatus','CustomerRipe','PersonInCharge','EntryPerson'])->where('entry_person_id', 'in', $this->childrenAdminIds)->paginate($limit, false, ['page' => $page])->toArray();

            return json(['code' => 200, 'msg' => '', 'total' => $result['total'], 'data' => $result['data']]);
        }
        return View::fetch();
    }

    //新增资源
    public function add(Request $request)
    {

        if ($request->isAjax()) {
            $data             = $request->param();
            $person_in_charge = $request->param('person_in_charge_id');
            if (empty($person_in_charge)) {
                # code...
                $data['person_in_charge_id'] = $this->auth->id; //为空时 当前人
            } else {
                $data['person_in_charge_id'] = $person_in_charge;
            }

            $data['entry_person_id'] = $this->auth->id;

            unset($data['file'], $data['pc_src'], $data['pc_name']);
            // halt($data); //客户基本信息
            $customer = \app\admin\model\Customer::create($data);
            //获取附件信息
            $pc_src  = $request->param('pc_src'); //文件地址
            $pc_name = $request->param('pc_name'); //文件名称
            if (!empty($pc_src) && !empty($pc_name)) {
                foreach ($pc_src as $key => $value) {
                    CustomerAppendix::create([
                        'customer_id' => $customer->id,
                        'path'        => $value,
                        'name'        => $pc_name[$key],
                    ]);
                }
            }
            if ($customer) {
                return json(['code' => 200, 'url' => '', 'msg' => '添加成功！']);
            }
            return json(['code' => 400, 'url' => '', 'msg' => '未知原因！']);

        }

        return View::fetch();
    }

    /**
     * 文件上传
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function upload(Request $request)
    {
        $files    = $request->file();
        $savename = [];
        foreach ($files as $key => $file) {
            $savename['src']  = \think\facade\Filesystem::disk('public')->putFile('customer_file', $file, 'uniqid'); # code...
            $savename['name'] = $file->getOriginalName();
        }

        $data = [

            "code" => 0,
            'msg'  => '',
            "data" => $savename,

        ];

        return json($data);
        # code...
    }


    /**
     * [edit description]
     * 编辑
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function edit(Request $request,$id)
    {
        $model = \app\admin\model\Customer::find($id);
        # code...
        if ($request->isAjax()) {
            $data             = $request->param();
            $person_in_charge = $request->param('person_in_charge_id');
            if (empty($person_in_charge)) {
                # code...
                $data['person_in_charge_id'] = $this->auth->id; //为空时 当前人
            } else {
                $data['person_in_charge_id'] = $person_in_charge;
            }
            $data['entry_person_id'] = $this->auth->id;
            unset($data['file'], $data['pc_src'], $data['pc_name']);
            // halt($data); //客户基本信息
            $customer = \app\admin\model\Customer::update($data);
            //获取附件信息
            $pc_src  = $request->param('pc_src'); //文件地址
            $pc_name = $request->param('pc_name'); //文件名称
            if (!empty($pc_src) && !empty($pc_name)) {
                foreach ($pc_src as $key => $value) {
                    CustomerAppendix::create([
                        'customer_id' => $customer->id,
                        'path'        => $value,
                        'name'        => $pc_name[$key],
                    ]);
                }
            }
            if ($customer) {
                return json(['code' => 200, 'url' => '', 'msg' => '修改成功！']);
            }
            return json(['code' => 400, 'url' => '', 'msg' => '未知原因！']);
        }
        View::assign('model',$model);
        View::assign('customer_appendix',$model->CustomerAppendix);
        View::assign('empty','<span class="empty">暂无附件文档</span>');
        return View::fetch();
    }

    /**
     * [appendix_del description] 删除文件编辑
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function appendix_del(Request $request)
    {
        if ($request->isAjax()) {
             $id = $request->param('id'); //id
             $type = $request->param('type'); //id
             if ($type == "all") {
                 $count =  CustomerAppendix::destroy(function($query) use($id){
                    $query->where('customer_id','=',$id);
                });
             }else{
                $ids = explode(',', $id);
                $count =  CustomerAppendix::destroy(array_values($ids));
             }
            if ($count) {
                return json(['code' => 200, 'url' => '', 'msg' => '删除成功！']);
            }
        }
    }

    /**
     * [del description] 删除项目
     * @param  Request $request [description]
     * @param  string  $ids     [description]
     * @return [type]           [description]
     */
    public function del(Request $request,$ids="")
    {
        if ($request->isAjax() && $ids) {
            $ids = explode(',', $ids);
            $count = \app\admin\model\Customer::destroy(array_values($ids));
            if ($count) {
                return json(['code' => 200, 'url' => '', 'msg' => '删除成功！']);
            }
        }
    }


    /**
     * [detail description]详情
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function detail(Request $request)
    {
        $id = $request->param('id');
        $model = \app\admin\model\Customer::with(['CustomerCity','CustomerIntention','CustomerStatus','CustomerRipe','PersonInCharge','EntryPerson'])->find($id);

        View::assign('model',$model);
        View::assign('customer_appendix',$model->CustomerAppendix);
        View::assign('empty','<span class="empty">暂无附件文档</span>');
        return View::fetch();
    }

    /**
     * [download description]附件下载
     * @param  string $id [description]
     * @return [type]     [description]
     */
    public function download($id = "")
    {
        $model = CustomerAppendix::find($id);

        $file = 'storage/'.$model->path;
        if (file_exists($file)) {
            downloadFile($file, $model->name);
        } else {
            echo "<script>alert('文件不存在')</script>";
        }
    }

    /**
     * [followUp description]写跟进
     * @param  Request $request [description]
     * @param  [type]  $id      [description]
     * @return [type]           [description]
     */
    public function followUp(Request $request,$id)
    {
       $model = \app\admin\model\Customer::with(['CustomerCity','CustomerIntention','CustomerStatus','CustomerRipe','PersonInCharge','EntryPerson'])->find($id);
       if ($request->isAjax()) {
          $data             = $request->param();
          $data['admin_id'] = $this->auth->id;
          $data['customer_id'] = $id;
          $update_status = $request->param('update_status_id');
          if (!empty($update_status) && $update_status !=0) {
             \app\admin\model\Customer::update(['customer_status_id'=>$update_status,'id'=>$id]);
          }
          $follow_time = $request->param('follow_time');
          if (!empty($follow_time)) {
               \app\admin\model\Customer::update(['follow_time'=>$follow_time,'id'=>$id]);
          }
          unset($data['id'],$data['file'], $data['pc_src'], $data['pc_name']);
          $follow = Follow::create($data);
            //获取附件信息
            $pc_src  = $request->param('pc_src'); //文件地址
            $pc_name = $request->param('pc_name'); //文件名称
            if (!empty($pc_src) && !empty($pc_name)) {
                foreach ($pc_src as $key => $value) {
                    FollowAppendix::create([
                        'follow_id' => $follow->id,
                        'follow_path'        => $value,
                        'follow_name'        => $pc_name[$key],
                    ]);
                }
            }
           if ($follow) {
                return json(['code' => 200, 'url' => '', 'msg' => '跟进成功！']);
            }
            return json(['code' => 400, 'url' => '', 'msg' => '未知原因！']);
       }
       View::assign('model',$model);
       return View::fetch();
    }

    public function deliver(Request $request,$ids)
    {
        if ($request->isAjax()) {
            $ids = explode(',', $ids);
            $data = [];
            $data_update = [];
            $result = \app\admin\model\Customer::where('id','in',$ids)->select();
            foreach ($result as $key => $value) {
               $data[] = $request->param();
               $data_update[$key]['id'] = $value->id;
               $data_update[$key]['person_in_charge_id'] = $request->param('d_admin_id');
               $data[$key]['c_id'] = $value->id;
               $data[$key]['c_admin_id'] = $value->person_in_charge_id;
            }
          $deliver = new Deliver();
          $deliver_result = $deliver->saveAll($data);
           if ($deliver) {
               $customer = new \app\admin\model\Customer();
               $customer->saveAll($data_update);
                 return json(['code' => 200, 'url' => '', 'msg' => '转交成功']);
           }
          return json(['code' => 400, 'url' => '', 'msg' => '未知原因！']);
        }
        return View::fetch();
    }
}